/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.unit;
import haxe.PosInfos;
import haxe.unit.TestResult;

class FlashDevelopTestResult extends TestResult {
	
	var buf:StringBuf;
	var pathToUnitTests:String;
	
	public function new(pathToUnitTests:String) {
		super();
		this.pathToUnitTests = pathToUnitTests;
	}

	public function printFailedToStdError() {
		#if neko
		buf = new StringBuf();
		for ( test in m_tests ) {
			if (test.success == false) {
				if ( test.posInfos != null ) {
					appendFormatedPosInfos(test.posInfos);
				} else {
					appendFormatedFileNameByClassNameAndBackTrace(test.classname, test.backtrace);
				}
				buf.add(" ");
				buf.add(test.classname.split(".").pop());
				buf.add(".");
				buf.add(test.method);
				buf.add(" : ");
				buf.add(test.error);
				buf.add("\n");
				//TODO Solve path problem - exception may occur in test code or production code
				//if (test.backtrace != null) {
				//	appendExceptionCauseInfo(test.backtrace);
				//}
			}
		}
		var stderr = neko.io.File.stderr();
		stderr.writeString(buf.toString());
		stderr.flush();
		#end
	}
	
	private function appendFormatedPosInfos(posInfos:PosInfos):Void {
		addExpectedFileNameForClass(posInfos.className);
		buf.add(":");
		buf.add(posInfos.lineNumber);
		buf.add(":");
	}
	
	private function appendFormatedFileNameByClassNameAndBackTrace(className:String, backtrace:String) {
		addExpectedFileNameForClass(className);
		var lineNumber = findLineNumberInBackTrace(className, backtrace);
		buf.add(":");
		buf.add(lineNumber);
		buf.add(":");
	}
	
	private function appendExceptionCauseInfo(backtrace:String) {
		var lines = backtrace.split("\n");
		var firstLine:String = lines.pop();
		buf.add(pathToUnitTests);
		buf.add(firstLine.substr(7));//"CALLED ".length = 7
		buf.add(".hx");
	}
	
	private function addExpectedFileNameForClass(className:String) {
		var filePath = className.split(".").join("/");
		buf.add(pathToUnitTests);
		buf.add(filePath);
		buf.add(".hx");
	}
	
	private function findLineNumberInBackTrace(className:String, backtrace:String):String {
		var lineNumber = "0";
		className = className.split(".").pop();
		if (backtrace != null) {
			var lines = backtrace.split("\n");
			for ( line in lines ) {
				if ( line.indexOf(className) > 0 ) {
					lineNumber = line.substr(line.lastIndexOf(" "));
					lineNumber = StringTools.trim(lineNumber);
					return lineNumber;
				}
			}
		}
		return lineNumber;
	}
}